import PureRunnableUnitImport from '../components/runnable-unit-import';
import * as RunnableGroupAction from 'actions/runnable-group';
import * as RunnableUnitAction from 'actions/runnable-unit';
import { popLayer } from 'actions';
import { getFetchStatus, invalidateCache } from 'actions/util';
import * as ReactRedux from 'react-redux';
import _ from 'lodash';

const mapStateToProps = (state, ownProps) => {
  const { runtimeId } = ownProps;
  const unitIds = state.runnableUnitIdsByRuntimeId[runtimeId] || [];
  const originUnits = _.values(_.pick(state.runnableUnitsById, unitIds));

  return {
    unitImportFetching: getFetchStatus(state, RunnableUnitAction.createUnit),
    mavenUnits: originUnits.filter(unit => unit.type === 'MAVEN' || unit.type === 'MAVEN_PARENT')
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  const { groupId, runtimeId } = ownProps;

  return {
    onUnitImport: (params) => {
      return dispatch(RunnableUnitAction.createUnit(Object.assign({}, params, { groupId, runtimeId })))
        .then(({ error, payload }) => {
          if (!!error) {
            return Promise.reject(payload.message);
          }
          invalidateCache(RunnableGroupAction.listUnitsByRuntimeId, runtimeId);
          dispatch(RunnableGroupAction.listUnitsByRuntimeId(runtimeId));
        });
    },
    popLayer: () => {
      dispatch(popLayer());
    }
  };
};

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(PureRunnableUnitImport);
